define(function (require, exports, module) {
    var angular = require('angular');
    var dialog = require("dialogplus");
    var api_prefix = G_CONFIG["api_prefix"]; //api前缀
    var ui = require("ui");
    var util = require("util");
    require("pagination");
    require("angular-ui");
    require("/public/js/plugins/select2/select2");
    var config = require('/public/js/myservice/config');

    angular.module('Invoice', ['ngUI', 'myNav'])
        .service('invoiceService', ['$rootScope',function ($rootScope){
            var service = {
                onInvoiceShow: function ($dialog, $dialogScope, invoiceType, oldInvoiceId) {
                    /**
                     * 打开发票编辑界面时初始化
                     * invoiceType: 发票类型：1：新建发票，2：新建主发票，3：复制发票，4：编辑发票，5：查看发票
                     * oldInvoiceId: 原发票id
                     */

                    //下拉框设置
                    //发票类别
                    $dialogScope.ddlConfigInvoiceCategory = {
                        allowClear: false,
                        data: [{id: 1, text: '服务票'}, {id: 0, text: '销售票'}],
                        minimumResultsForSearch: 'Infinity'
                    };

                    //发票类型
                    $dialogScope.ddlConfigInvoiceType = {
                        allowClear: false,
                        data: [{id: 0, text: '增值税普通发票'}, {id: 1, text: '增值税专用发票'}],
                        minimumResultsForSearch: 'Infinity'
                    };

                    //摘要类型
                    $dialogScope.ddlConfigInvoiceSummaryType = {
                        allowClear: false,
                        data: [{id: '软件技术服务费', text: '软件技术服务费'}, {id: '软件服务费', text: '软件服务费'}],
                        minimumResultsForSearch: 'Infinity'
                    };

                    //申请人
                    $dialogScope.ddlConfigInvoiceProposer = {
                        allowClear: false,
                        ajax: {
                            url: api_prefix + "erp-interface/get-users",
                            dataType: 'json',
                            delay: 250,
                            data: function (term) {
                                return {
                                    keyword: term,
                                    limit: 10
                                };
                            },
                            results: function (json, page) {
                                var data = [];
                                if (json.retCode === "0") {
                                    data = json.data;
                                }
                                return {results: data};
                            },
                            processResults: function (data, page) {
                                return {
                                    results: data.items
                                };
                            },
                            cache: true
                        },
                        escapeMarkup: function (markup) {
                            return markup;
                        }, // let our custom formatter work
                        minimumInputLength: 1,
                        onchange2: function (newVal) {
                            $dialogScope.invoiceInfo.user_name = newVal.UserName;
                            $dialogScope.invoiceInfo.area_name = newVal.BUName;
                        },
                        formatResult: formatProposer,
                        formatSelection: formatProposerSelection // omitted for brevity, see the source of this page
                    };
                    function formatProposer(repo) {
                        if (repo.loading) return repo.text;

                        var markup = '<div class="clearfix" style="width: 300px;">' +
                            '<div class="clearfix">' +
                            '<div class="col-sm-6">' + repo.UserName + '</div>' +
                            '<div class="col-sm-18">' + repo.BUName + '</div>' +
                            '</div></div>';

                        return markup;
                    }
                    function formatProposerSelection(repo) {
                        return repo.text;
                    }

                    //开票单位
                    $dialogScope.ddlConfigInvoiceCompany = {
                        allowClear: false,
                        data: [],
                        onchange2: function (newVal) {
                            $dialogScope.invoiceInfo.invoice_company_name = newVal.BUName;
                        }
                    };
                    var getInvoiceBusinessUnit = function () {
                        /**
                         * 获取开票单位
                         */
                        var get_data = {keyword: ''};
                        var url = api_prefix + "/invoice/get-invoice-business-unit";
                        var ddlData = [];
                        $.ajax({
                            url: url,
                            type: "GET",
                            dataType: 'json',
                            data: get_data,
                            success: function (json) {
                                if (json.retCode == 0) {
                                    var items = json.data;
                                    var item;
                                    for(i = 0; item = items[i]; i++){
                                        ddlData.push({
                                            id: item.BUGUID,
                                            text: item.BUName
                                        })
                                    }
                                    $dialogScope.ddlConfigInvoiceCompany.data = ddlData;
                                    $dialogScope.$applyAsync();

                                } else {
                                    util.alert("获取开票单位失败：" + json.errMsg);
                                }
                            }
                        });
                    }();

                    //初始化发票信息
                    $dialogScope.invoiceInfo = {
                        is_main_invoice: '0',
                        invoice_category: '1',
                        invoice_type: '0',
                        invoiceSummarys: [{}],
                        invoiceDocuments: []
                    };

                    //新建主发票
                    if(invoiceType == 2){
                        $dialogScope.invoiceInfo.is_main_invoice = '1';
                    }

                    //获取现有发票信息
                    if(oldInvoiceId){
                        $.ajax({
                            url: api_prefix + 'invoice/get-invoice-info',
                            type: 'get',
                            dataType: 'json',
                            data: {invoiceId: oldInvoiceId},
                            success: function (res) {
                                if (res.retCode === "0") {
                                    var invoiceData = res.data;
                                    var t1 = setInterval(function(){
                                        if(invoiceData){
                                            setTimeout(function(){
                                                clearInterval(t1);
                                            },500);

                                            $dialogScope.invoiceInfo = invoiceData;

                                            //复制发票清空信息
                                            if(invoiceType == 3){
                                                $dialogScope.invoiceInfo.invoice_id = '';
                                                $dialogScope.invoiceInfo.contract_id = '';
                                                $dialogScope.invoiceInfo.is_child_invoice = '';
                                                $dialogScope.invoiceInfo.is_lose = '';
                                                $dialogScope.invoiceInfo.is_receipt = '';
                                                $dialogScope.invoiceInfo.is_red_invoice = '';
                                                $dialogScope.invoiceInfo.payment_amount = '';
                                                $dialogScope.invoiceInfo.receivables_amount = '';
                                                $dialogScope.invoiceInfo.red_by_invoice_id = '';

                                            }

                                            //查看发票
                                            if (invoiceType == 5) {
                                                $dialogScope.invoiceInfo.editMode = 1;
                                            }

                                            //获取申请人和开票单位
                                            if($dialogScope.invoiceInfo.user_name){
                                                $('#idProposer').select2("data", {
                                                    id: $dialogScope.invoiceInfo.proposer_id,
                                                    text: $dialogScope.invoiceInfo.user_name
                                                });
                                            }
                                            $dialogScope.$applyAsync();
                                        }
                                    },10);

                                }else{
                                    util.alert(res.errMsg);
                                }
                            },
                            error: function () {
                                util.alert('系统维护，请稍候重试');
                            }
                        });
                    }


                    //新建发票摘要
                    $dialogScope.newInvoiceAbstract = function () {
                        var items = $dialogScope.invoiceInfo.invoiceSummarys;
                        var summary = {};
                        items.push(summary);
                    };

                    //删除发票摘要
                    $dialogScope.removeInvoiceAbstract = function (idx) {
                        $dialogScope.invoiceInfo.invoiceSummarys.splice(idx,1);
                    };

                    //附件上传初始化
                    $('#fileupload').fileupload({
                        dataType: 'json',
                        url: api_prefix + "/common/file/upload-document&XDEBUG_SESSION_START=netbeans-xdebug",
                        acceptFileTypes: /(\.|\/)(xls?x|doc?x|pdf|msg)$/i,
                        maxFileSize: 10000000,
                        add:function(e,data){
                            // 大小限制
                            if(data.files.length>0){
                                if(data.files[0].size>config.uploader.max_file_size){
                                    util.alert('文件大小超出'+config.uploader.max_file_size_text+'，无法上传。');
                                    return;
                                }
                            }
                            data.submit();
                            ui.loading('','正在上传…');
                            $("#fileupload_error").hide();
                        },
                        done: function (e, data) {
                            var res = data.result;
                            if(res.retCode == "0"){
                                ui.removeLoading();
                                var document ={
                                    __type: 'add',
                                    document_id:data._time,
                                    document_name:data.files[0].name,
                                    document_ext_name:'',
                                    document_path:res.data.path,
                                    business_id:''
                                } ;
                                if(!$dialogScope.invoiceInfo.invoiceDocuments){
                                    $dialogScope.invoiceInfo.invoiceDocuments = [];
                                }
                                $dialogScope.invoiceInfo.invoiceDocuments.push(document);
                                $dialogScope.$applyAsync();

                                $("#fileupload_error").html("");
                                $("#fileupload_error").hide();
                            }else{
                                ui.removeLoading();
                                $("#fileupload_error").html("上传失败:" + res.errMsg);
                                $("#fileupload_error").show();
                            }
                        },
                        fail: function(e, data) {
                            $("#fileupload_error").html("上传失败:" + data.errorThrown);
                            $("#fileupload_error").show();
                            ui.removeLoading();
                        },
                        always: function(e, data) {
                            ui.removeLoading();
                        }
                    });

                    /**
                     * 删除附件
                     * @param data
                     * @param id
                     */
                    $dialogScope.delAttachment =function(item,idx){
                        if (item.__type == 'add') {
                            $dialogScope.invoiceInfo.invoiceDocuments.splice(idx, 1);
                        } else {
                            angular.extend(item, {__type: 'delete'});
                        }
                        $dialogScope.$applyAsync();
                    };

                    $dialogScope.$applyAsync();

                },
                editInvoiceSave: function ($data, $dialog, $dialogScope, callback,pageIndex) {
                    var item = $dialogScope.invoiceInfo;

                    //校验
                    if ($('.error:visible').length) {
                        return false;
                    }

                    if(item.invoice_code.length>20){
                        util.alert('发票代码不能大于20字符');
                        return false
                    }

                    if(item.invoice_no.length>20){
                        util.alert('发票号码不能大于20字符');
                        return false
                    }

                    if(item.customer_name.length>20){
                        util.alert('客户名称不能大于20字符');
                        return false
                    }

                    if(!(parseFloat(item.invoice_amount)>0)){
                        util.alert('开票金额必须大于0');
                        return false
                    }else if(item.invoice_amount.length>20){
                        util.alert('开票金额不能大于20字符');
                        return false
                    }

                    if(item.remark && item.remark.length>50){
                        util.alert('备注不能大于50字符');
                        return false
                    }
                    //发票摘要
                    var summarys = item.invoiceSummarys;
                    var summary;
                    var sum = 0;
                    for(var i = 0;summary = summarys[i];i++){
                        if(!(parseFloat(summary.summary_amount)>0)){
                            util.alert('摘要金额必须大于0');
                            return false
                        }else if(summary.summary_amount.length>20){
                            util.alert('摘要金额不能大于20字符');
                            return false
                        }

                        //计算摘要金额总和
                        sum += parseFloat(summary.summary_amount);
                    }

                    /**
                     * 判断开票金额是否与摘要金额相等
                     */
                    if(item.invoice_amount != sum){
                        util.alert('开票金额与摘要金额总和不相等');
                        return false
                    }

                    var url = api_prefix + 'invoice/save-invoice';
                    $.ajax({
                        url: url,
                        type: 'post',
                        dataType: 'json',
                        data: item,
                        success: function (res) {
                            if (res.retCode == "0") {
                                $dialog.close();
                                util.alert('保存成功');
                                if (callback) {
                                    callback(pageIndex);
                                }
                            }else{
                                util.alert(res.errMsg);
                            }
                        },
                        error: function () {
                            util.alert('系统维护，请稍候重试');
                        }
                    });
                    return false
                }
            };

            return service;
        }])
        .controller('invoiceListCtrl',['$scope','invoiceService', 'appservice', function ($scope,invoiceService, appservice) {
            appservice.name = '明源云客-发票管理';
            $scope.invoiceService = invoiceService;

            //发票列表
            $scope.invoices = [];

            //筛选列表
            $scope.filterDataType = [{
                name: '全部', selected: true, value: '-1'
            }, {
                name: '主发票', value: '1'
            }, {
                name: '普通发票', value: '0'
            }];
            $scope.filterDataStatus = [{
                name: '全部', selected: true, value: '-1'
            }, {
                name: '未/部分关联', value: '0'
            }, {
                name: '已全部关联', value: '1'
            }];

            $scope.changeType = function (Type) {
                $scope.query.execute();
            };
            $scope.changeStatus = function (status) {
                $scope.query.execute();
            };

            /**
             * 判断查询时间
             * @param a
             * @param b
             * @returns {boolean}
             */
            var compareDate = function(a,b){
                if(a){
                    var arrA = a.split("-");
                    var start = new Date(arrA[0],arrA[1],arrA[2]);
                    var startTime = start.getTime();
                }

                if(b){
                    var arrB = b.split("-");
                    var end = new Date(arrB[0],arrB[1],arrB[2]);
                    var endTime = end.getTime();
                }

                if(startTime && endTime && startTime > endTime){
                    return true
                }else{
                    return false
                }
            };

            //查询条件
            $scope.query = {
                searchKey: '',
                invoice_begin_date: '',
                invoice_end_date: '',
                execute: function (page) {
                    var pageInx = page || 1;
                    var parms = {
                        searchKey: this.searchKey,
                        invoice_begin_date: this.invoice_begin_date,
                        invoice_end_date: this.invoice_end_date,
                        pageIndex: page,
                        pageSize: 10
                    };

                    if(compareDate(this.invoice_begin_date,this.invoice_end_date)){
                        util.alert('开始时间不得大于结束时间');
                        return
                    }
                    //收集过滤条件
                    var filterType = $.grep($scope.filterDataType, function (o, n) {
                        return o.selected == true;
                    });
                    if (filterType.length) {
                        parms.is_main_invoice = filterType[0].value;
                    }
                    var filterStatus = $.grep($scope.filterDataStatus, function (o, n) {
                        return o.selected == true;
                    });
                    if (filterStatus.length) {
                        parms.invoice_status = filterStatus[0].value;
                    }

                    var url = api_prefix + 'invoice/get-invoice-list-by-page';

                    $.ajax({
                        url: url,
                        type: 'get',
                        dataType: 'json',
                        data: parms,
                        success: function (res) {
                            if (res.retCode === "0") {
                                var data = res.data;
                                $scope.invoices = data.items;
                                $scope.total = data.total;
                                $scope.$applyAsync();
                                $scope.getPage(pageInx);
                            }else{
                                util.alert(res.errMsg);
                            }
                        },
                        error: function () {
                            util.alert( '系统维护，请稍候重试！');
                        }
                    });
                }
            };

            //删除发票
            $scope.removeInvoice = function (id) {
                util.confirm('确定要删除此发票吗？', {
                    ok: function () {
                        var url = api_prefix + 'invoice/delete-invoice';

                        $.ajax({
                            url: url,
                            type: 'get',
                            dataType: 'json',
                            data: {invoiceId: id},
                            success: function (res) {
                                if (res.retCode === "0") {
                                    $scope.query.execute($scope.page_index);
                                    util.alert('删除成功');
                                }else{
                                    util.alert(res.errMsg);
                                }
                            },
                            error: function () {
                                util.alert('系统维护，请稍候重试！');
                            }
                        });
                    }
                });
            };

            //标记遗失
            $scope.markLoss = function (id) {
                util.confirm('确定标记遗失此发票吗？', {
                    ok: function () {
                        var url = api_prefix + 'invoice/do-lose';

                        $.ajax({
                            url: url,
                            type: 'get',
                            dataType: 'json',
                            data: {invoiceId: id},
                            success: function (res) {
                                if (res.retCode === "0") {
                                    $scope.query.execute($scope.page_index);
                                    util.alert('标记成功')
                                }else{
                                    util.alert(res.errMsg);
                                }
                            },
                            error: function () {
                                util.alert('系统维护，请稍候重试！');
                            }
                        });
                    }
                });
            };


            //翻页控件
            $scope.getPage = function (page) {
                var pageInx = $scope.page_index = page || 1;
                $scope.startPageIndex = (pageInx - 1)*10;
                $('#pagination').pagination($scope.total, {
                    current_page: pageInx - 1,
                    num_edge_entries: 1, //边缘页数
                    num_display_entries: 4, //主体页数
                    callback: function (page_index, jq) {
                        $scope.page_index = page_index;
                        $scope.startPageIndex = (page_index - 1)*10;
                        $scope.query.execute(page_index);
                    },
                    items_per_page: 10 //每页显示10项
                });
            };


            //页面初始化
            $scope.init = function () {
                $scope.query.execute();
            };
            $scope.init();
        }]);
});